package com.imooc.authorization.dao;

import com.imooc.authorization.common.BaseDAO;
import com.imooc.authorization.entity.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

/**
 * Created by Administrator on 2016/8/21.
 */

@Repository
public class UserDAO extends BaseDAO {


    private class UserMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet rs, int i) throws SQLException {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setPassword(rs.getString("pwd"));

            return user;
        }
    }

    /**
     * 根据用户名、密码查询用户，用于登陆
     * @param name 用户名
     * @param pwd   密码
     * @return 查询到胡唯一用户实体
     */


    public User findUser(String name, String pwd){

        String sql = "select * from auth_user where name=? and pwd=?";

        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql,new Object[]{name,pwd},new UserMapper());

        } catch (DataAccessException e) {
            System.out.print("登陆失败！");
        }


        return user;
    }

    public void save(User user){
        String sql = "insert into auth_user(id,name,pwd) values(?,?,?)";
        jdbcTemplate.update(sql,user.getId(),user.getName(),user.getPassword());

    }

    public void deleteById(Long id){
        String sql="delete from auth_user where id=?";

        jdbcTemplate.update(sql,id);

    }

    public void update(User user){
        String sql="update auth_user set name=?,pwd=? where id=?";
        jdbcTemplate.update(user.getName(),user.getPassword(),sql,user.getId());

    }

    public User findById(Long id){
        String sql="select * from auth_user where id=?";

        User user = null;
        try {
            user = jdbcTemplate.queryForObject(sql,new Object[]{id},new UserMapper());

        } catch (DataAccessException e) {
            System.out.print("登陆失败！");
        }
        return user;
    }

    public Collection<User> findByIds(Collection<Long> ids){
        StringBuilder sql=new StringBuilder("select * from auth_user where in (");

        ids.forEach((id) ->  sql.append(id).append("?,"));
        sql.deleteCharAt(sql.length() - 2);
        sql.append(")");

        return jdbcTemplate.query(sql.toString(),ids.toArray(),new UserMapper());
    }

    public Collection<User> findPage(int page,int size){

        if(page <1 ){

            page = 1;
        }
        if(size < 0){

            size = 20;
        }

        String sql="select * from auth_user limit ?,?";
        int skip = (page-1)*size;

        return jdbcTemplate.query(sql,new Object[]{skip,size},new UserMapper());
    }



}
